package com.cyl.manager.yee.controller;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.cyl.manager.yee.convert.YeeMerchantSifConvert;
import com.cyl.manager.yee.domain.YeeMerchantSif;
import com.cyl.manager.yee.pojo.query.YeeMerchantSifAdd;
import com.cyl.manager.yee.pojo.query.YeeMerchantSifCwsp;
import com.cyl.manager.yee.pojo.query.YeeMerchantSifQuery;
import com.cyl.manager.yee.pojo.vo.YeeMerchantSifVO;
import com.cyl.manager.yee.service.YeeMerchantSifService;
import com.cyl.sms.service.SmsService;
import com.cyl.yeepay.setvice.YeePayService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.model.SmsResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.SysConfig;
import com.ruoyi.system.service.ISysConfigService;
import com.yeepay.yop.sdk.service.account.model.BalanceQueryAccountInfoRespDTOResult;
import com.yeepay.yop.sdk.service.account.model.ReceiptGetReceiptRespDTOResult;
import com.yeepay.yop.sdk.service.account.model.WithdrawOrderWithdrawOrderRespDTOResult;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
/**
 * 结算记录Controller
 *
 * @author zcc
 * @date 2025-03-10
 */
@Api(description ="结算记录接口列表")
@RestController
@RequestMapping("/yee/yeeMerchantSif")
public class YeeMerchantSifController extends BaseController {
    @Autowired
    private YeeMerchantSifService service;
    @Autowired
    private YeeMerchantSifConvert convert;
    
    @Autowired
    private YeePayService yeePayService;
   
    @Autowired
    private SmsService smsService;
    
    @Autowired
    private ISysConfigService configService;
    
	  /**
	  * 	获取系统保留余额配置配置信息
	  */
	 @GetMapping("/getConfig")
	 public ResponseEntity<SysConfig> getConfig(){
	    return ResponseEntity.ok(getYeSysConfig());
	 }
    
	 private SysConfig getYeSysConfig() {
		 return configService.selectConfigByKey2("SYS_ZJYEBD_PZ");
	 }
    @ApiOperation("查询结算记录列表")
    @PreAuthorize("@ss.hasPermi('yee:yeeMerchantSif:list')")
    @PostMapping("/list")
    public ResponseEntity<Page<YeeMerchantSif>> list(@RequestBody YeeMerchantSifQuery query, Pageable page) {
    	Long qrDeptZbjId = SecurityUtils.getDeptZbjId();
        if(qrDeptZbjId!=null) {
        	query.setDeptZbjId(qrDeptZbjId);
        }
        List<YeeMerchantSif> list = service.selectList(query, page);
        return ResponseEntity.ok(new PageImpl<>(list, page, ((com.github.pagehelper.Page)list).getTotal()));
    }
    
    // TRANSFER:企业账户转账  	PAY:企业付款  	RECHARGE:企业账户充值  	WITHDRAW:企业账户提现  	 ADVANCE:记账薄收款
    //  ORDER_REMIT:订单付款	 GROUP_ACCOUNT_TRANSFER:资金归集 	 BANK_ACCOUNT_WITHDRAW:银行清分提现
    @ApiOperation("电子回单-下载")
    @PreAuthorize("@ss.hasPermi('yee:yeeMerchantSif:list')")
    @GetMapping("/receiptGet")
    public ResponseEntity<ReceiptGetReceiptRespDTOResult> receiptGet(String tradeType,String orderNo) {
        return ResponseEntity.ok(yeePayService.receiptGet(tradeType, orderNo));
    }
 


    @ApiOperation("导出结算记录列表")
    @PreAuthorize("@ss.hasPermi('yee:yeeMerchantSif:export')")
    @Log(title = "结算记录", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public ResponseEntity<String> export(YeeMerchantSifQuery query) {
    	Long qrDeptZbjId = SecurityUtils.getDeptZbjId();
        if(qrDeptZbjId!=null) {
        	query.setDeptZbjId(qrDeptZbjId);
        }
        List<YeeMerchantSif> list = service.selectList(query, null);
        ExcelUtil<YeeMerchantSifVO> util = new ExcelUtil<>(YeeMerchantSifVO.class);
        return ResponseEntity.ok(util.writeExcel(convert.dos2vos(list), "结算记录数据"));
    }

    @ApiOperation("获取结算记录详细信息")
    @PreAuthorize("@ss.hasPermi('yee:yeeMerchantSif:query')")
    @GetMapping(value = "/{id}")
    public ResponseEntity<YeeMerchantSif> getInfo(@PathVariable("id") Long id) {
        return ResponseEntity.ok(service.selectById(id));
    }

    @ApiOperation("出纳发起他卡结算")
    @PreAuthorize("@ss.hasPermi('yee:yeeMerchantSif:add')")
    @Log(title = "出纳发起他卡结算", businessType = BusinessType.INSERT)
    @PostMapping("/tkjs")
    public ResponseEntity<YeeMerchantSif> tkjs(@RequestBody YeeMerchantSifAdd yeeMerchantSifAdd) {
    	yeeMerchantSifAdd.setJsfl("11");//11 他卡结算 12供应商结算 13提现结算
        checkZhye(yeeMerchantSifAdd.getOrderAmount(), service.getFeeAmount(yeeMerchantSifAdd.getOrderAmount(), "11")); 
        return ResponseEntity.ok(service.startSif(yeeMerchantSifAdd));
    }
    
    // 12供应商结算 13
    @ApiOperation("出纳发起供应商结算")
    @PreAuthorize("@ss.hasPermi('yee:yeeMerchantSif:add')")
    @Log(title = "出纳发起供应商结算", businessType = BusinessType.INSERT)
    @PostMapping("/gysjs")
    public ResponseEntity<YeeMerchantSif> gysjs(@RequestBody YeeMerchantSifAdd yeeMerchantSifAdd) {
    	yeeMerchantSifAdd.setJsfl("12");//11 他卡结算 12供应商结算 13提现结算
        checkZhye(yeeMerchantSifAdd.getOrderAmount(), service.getFeeAmount(yeeMerchantSifAdd.getOrderAmount(), "12")); 
        return ResponseEntity.ok(service.startSif(yeeMerchantSifAdd));
    }
    
    // 12供应商结算 13
    @ApiOperation("出纳发起提现结算")
    @PreAuthorize("@ss.hasPermi('yee:yeeMerchantSif:add')")
    @Log(title = "出纳发起提现结算", businessType = BusinessType.INSERT)
    @PostMapping("/txjs")
    public ResponseEntity<YeeMerchantSif> txjs(@RequestBody YeeMerchantSifAdd yeeMerchantSifAdd) {
    	yeeMerchantSifAdd.setJsfl("13");//11 他卡结算 12供应商结算 13提现结算
        checkZhye(yeeMerchantSifAdd.getOrderAmount(), service.getFeeAmount(yeeMerchantSifAdd.getOrderAmount(), "13")); 
        return ResponseEntity.ok(service.startSif(yeeMerchantSifAdd));
    }
    
    
    
  @ApiOperation("财务审批结算")
  @PreAuthorize("@ss.hasPermi('yee:yeeMerchantSif:edit')")
  @Log(title = "财务审批结算", businessType = BusinessType.UPDATE)
  @PutMapping("/cwspSatrt")
  public ResponseEntity<Integer> cwspSatrt(@RequestBody YeeMerchantSifCwsp yeeMerchantSifCwsp) {
  	  String spjg = yeeMerchantSifCwsp.getSpjg();
	  if(spjg.equals("2")) {
		  //验证码验证
		  smsService.checkCode(SecurityUtils.getLoginUser().getUser().getPhonenumber(), yeeMerchantSifCwsp.getUuid(), yeeMerchantSifCwsp.getCode());
	      YeeMerchantSif yeeMerchantSif =  service.selectById(yeeMerchantSifCwsp.getId());
	      //资金账户验证
	      checkZhye(yeeMerchantSif.getOrderAmount(), yeeMerchantSif.getFeeAmount());
	      
	      
	  }
      return ResponseEntity.ok(service.cwspSatrt(yeeMerchantSifCwsp));
  }
    
  @ApiOperation("财务提现失败再次发起")
  @PreAuthorize("@ss.hasPermi('yee:yeeMerchantSif:edit')")
  @Log(title = "财务提现失败再次发起", businessType = BusinessType.UPDATE)
  @PutMapping("/d2bAddB2cSatrt")
  public ResponseEntity<Integer> d2bAddB2cSatrt(@RequestBody YeeMerchantSifCwsp yeeMerchantSifCwsp) {
	  YeeMerchantSif yeeMerchantSif = service.selectById(yeeMerchantSifCwsp.getId());
      //资金账户验证
      checkZhye(yeeMerchantSif.getOrderAmount(), yeeMerchantSif.getFeeAmount());
      
	  if(!"2".equals(yeeMerchantSif.getJszt())) {//2财务审批通过3财务审批不通过
          throw new RuntimeException("财务审批通过的才能发起！");
	  }
	  if("2".equals(yeeMerchantSif.getB2bZt())) {//到账状态1处理中2成功3失败
          throw new RuntimeException("提现状态为失败的才能发起！");
	  }
      return ResponseEntity.ok(service.d2bAddB2cSatrt(yeeMerchantSif));
  }
  
  @ApiOperation("财务到账失败再次发起")
  @PreAuthorize("@ss.hasPermi('yee:yeeMerchantSif:edit')")
  @Log(title = "财务到账失败再次发起", businessType = BusinessType.UPDATE)
  @PutMapping("/d2cSatrt")
  public ResponseEntity<Integer> d2cSatrt(@RequestBody YeeMerchantSifCwsp yeeMerchantSifCwsp) {
	  YeeMerchantSif yeeMerchantSif = service.selectById(yeeMerchantSifCwsp.getId());
	  if(!"2".equals(yeeMerchantSif.getJszt())) {
          throw new RuntimeException("财务审批通过的才能发起！");
	  }
	  // 1处理中2成功3失败
//	  if(!"2".equals(yeeMerchantSif.getB2bZt())) {
//          throw new RuntimeException("提现状态为失败的才能发起！");
//	  }
	  if("2".equals(yeeMerchantSif.getB2cZt())) {
          throw new RuntimeException("到账状态为失败的才能发起！");
	  }
      return ResponseEntity.ok(service.d2cSatrt(yeeMerchantSif));
  }
  
  
  @ApiOperation("直接提现")
  @PreAuthorize("@ss.hasPermi('yee:yeeMerchantSif:editadmin')")
  @Log(title = "直接提现", businessType = BusinessType.UPDATE)
  @PostMapping("/transferB2cOrder")
  public ResponseEntity<WithdrawOrderWithdrawOrderRespDTOResult> transferB2cOrder(@RequestBody YeeMerchantSif yeeMerchantSif) {
      return ResponseEntity.ok(yeePayService.transferB2cOrder(yeeMerchantSif));
  }
  

  /**
  * 	获取可用余额 /yee/yeeMerchantSif
  */
 @GetMapping("/getKyBalance")
 public ResponseEntity<Map<String, Object>> getKyBalance(){
		  SysConfig sysConfig =  getYeSysConfig();//配置
		  Map<String, Object> map = new HashMap<String, Object>();
		  if(sysConfig==null) {
	          throw new RuntimeException("资金账户保底余额未配置，请联系管理员！");
		  }
		  BigDecimal bdBalance = null;//保底余额
		  try {
			  String bdpz = sysConfig.getConfigValue();
			  bdBalance =  new BigDecimal(bdpz);//保底余额
		  } catch (Exception e) {
		      throw new RuntimeException("资金账户保底余额配置有误，请联系管理员！");
		  }
 		  BalanceQueryAccountInfoRespDTOResult result =  yeePayService.balanceQueryByZj();//资金账户余额
		  if(result!=null && result.getBalance()!=null) {
			  BigDecimal zjBalance = result.getBalance();//资金账户余额
			  map.put("zjBalance", zjBalance);//账户资金金额
			  map.put("bdBalance", bdBalance);//账户保底金额
			  map.put("kyBalance", zjBalance.subtract(bdBalance));//账户可用金额
			  map.put("bdRemark", sysConfig.getRemark());//保底金额解释
			  map.put("dxPhone",  getPhone());//短信电话号码
		      return ResponseEntity.ok(map);
		  }else {
		      throw new RuntimeException("获取资金账户繁忙，请稍后重试！");
		  }
 }
 
  /**
   * 
   */
  private boolean  checkZhye(BigDecimal orderAmount,BigDecimal feeAmount) {
      BigDecimal zzAmount = orderAmount.add(feeAmount);//转账金额
	  SysConfig sysConfig =  getYeSysConfig();//配置
	  if(sysConfig==null) {
          throw new RuntimeException("资金账户保底余额未配置，请联系管理员！");
	  }
	  BigDecimal bdye = null;//保底余额
	  try {
		  String bdpz = sysConfig.getConfigValue();
		  bdye =  new BigDecimal(bdpz);//保底余额
	  } catch (Exception e) {
	      throw new RuntimeException("资金账户保底余额配置有误，请联系管理员！");
	  }
      BigDecimal ygAmount = zzAmount.add(bdye);//转账需要的资金账户余额
	  BalanceQueryAccountInfoRespDTOResult result =  yeePayService.balanceQueryByZj();//资金账户余额
	  if(result!=null && result.getBalance()!=null) {
		  BigDecimal balance = result.getBalance();//资金账户余额
		  if (ygAmount.compareTo(balance) < 0) {
		      return true;//满足资金账号余额够
		  }else {
			  throw new RuntimeException("操作失败，操作后资金账户保底余额不足。保底余额："+bdye.toString()+"元，资金账户余额:"+balance.toString()+"元,交易金额："+zzAmount+"元(含手续费)，保底余额解释："
					  + sysConfig.getRemark()
					  );
		  }
	  }else {
	      throw new RuntimeException("获取资金账户繁忙，请稍后重试！");
	  }
  }
  
	@ApiOperation("修改结算记录")
	@PreAuthorize("@ss.hasPermi('yee:yeeMerchantSif:edit')")
	@Log(title = "结算记录", businessType = BusinessType.UPDATE)
	@PutMapping
	public ResponseEntity<Integer> edit(@RequestBody YeeMerchantSif yeeMerchantSif) {
	    return ResponseEntity.ok(service.update(yeeMerchantSif));
	}
	
  private String getPhone() {
	return SecurityUtils.getLoginUser().getUser().getPhonenumber();
  }  
  
}
